package com.qf.SpringSecurity;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * @ClassName: SecurityConfig
 * @Author: WangHao
 * @Date: 2025/5/7 9:55
 * @Description: 通过 WebSecurityConfigurerAdapter 配置认证规则
 * @Version: 1.0
 */
@Configuration
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true) // 开启注解,启用@Secured和@PreAuthorize等
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private MyUserDetailsService userDetailsService;

    /**
     * 认证失败处理类
     */
    @Autowired
    private AuthenticationEntryPointImpl unauthorizedHandler;

    /**
     * 授权失败处理类
     */
    @Autowired
    private MyAccessDeniedHandler myAccessDeniedHandler;

    @Autowired
    private JwtAuthenticationTokenFilter authenticationTokenFilter;

    // 新增代码，用于获取AuthenticationManager对象，在登录的业务层进行调用
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    // 用户认证
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        // 指定加密方式
        // auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder());

        // 后端密码是没有加密的，所以这里直接进行原文对比
        auth.userDetailsService(userDetailsService).passwordEncoder(new PasswordEncoder( ) {
            @Override
            public String encode(CharSequence rawPassword) {
                return rawPassword.toString();
            }

            // 匹配密码
            @Override
            public boolean matches(CharSequence rawPassword, String encodedPassword) {
                return encodedPassword.equals(rawPassword.toString());
            }
        });
    }

    // 权限认证

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        /**
         * 注解时的拦截规则
         */
        http.authorizeRequests()
                // 允许任何人访问，不管是否登录
                .antMatchers("/**/*.js", "/**/*.css","/user/login","/user/info","/user/logout","/register").permitAll()
                // 其他资源需要认证后才能访问，比如/hello
                .antMatchers("/**").authenticated();
                // .and().formLogin(); // 禁止表单登录，使用自己的登录接口
        http.csrf().disable(); // 禁用csrf,否则post请求会失效
        // 认证失败处理类
        // http.exceptionHandling(exception -> exception.authenticationEntryPoint(unauthorizedHandler));

        // 基于token，不需要session，即所有认证信息都在token中，所以不需要session
        http.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS));

        // 指定权限异常处理类
        http.exceptionHandling().authenticationEntryPoint(unauthorizedHandler);
        http.exceptionHandling().accessDeniedHandler(myAccessDeniedHandler);

        // 添加JWT filter
        http.addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
    }
}
